package com.ant.business.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.sprite.utils.http.*;
import com.sprite.utils.io.UtilIO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * @description: OSS
 * @author: yy
 * @date: 2023/8/16 21:45
 */

@Component
public class AliyunOSS {
    @Value("${aliyun.endpoint}")
    public String endpoint;
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    public AliyunOSS() {
    }

    public PutObjectResult upload(String bucketName, String objName, InputStream inputStream, ObjectMetadata objectMetadata) {
        OSS ossClient = (new OSSClientBuilder()).build(this.endpoint, this.accessKeyId, this.accessKeySecret);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objName, inputStream, objectMetadata);
        PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
        return putObjectResult;
    }

    public PutObjectResult upload(String bucketName, String objName, String url, ObjectMetadata objectMetadata) throws Exception {
        HttpResponse response = UtilHttp.request(url, "GET", (Headers) null, (UrlParams) null, (RequestPayload) null);
        String contentType = response.getHeader("Content-Type");
        String charset = null;
        if (null != contentType) {
            objectMetadata.setContentType(contentType);
        } else {
            ContentType ctType = ContentType.resolve(contentType);
            charset = ctType.getCharset();
        }

        InputStream inputStream = response.getInputStream();
        if (response.getStatusCode() != 200) {
            throw new HttpException(response.getStatusCode(), response.getStatusMessage(), UtilIO.readToText(inputStream, charset));
        } else {
            OSS ossClient = (new OSSClientBuilder()).build(this.endpoint, this.accessKeyId, this.accessKeySecret);
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objName, inputStream, objectMetadata);
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            ossClient.shutdown();
            return putObjectResult;
        }
    }

    public PutObjectResult upload(PutObjectRequest putObjectRequest) {
        OSS ossClient = (new OSSClientBuilder()).build(this.endpoint, this.accessKeyId, this.accessKeySecret);
        PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
        return putObjectResult;
    }

    public OSS buildOSS() {
        return (new OSSClientBuilder()).build(this.endpoint, this.accessKeyId, this.accessKeySecret);
    }
}
